from flask import Flask, redirect, url_for, render_template, request, jsonify
from routes.add_ip import add_ip_bp
from flask_login import LoginManager, current_user, login_user, logout_user,login_required
from data import PostgreSQLWrapper
app = Flask(__name__)

app.register_blueprint(add_ip_bp)
app.secret_key = 'your_secret_key'

login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    db = PostgreSQLWrapper()
    user = db.get_user_by_id(user_id)
    print("登录",user)
    return user

@app.route('/')
def index():
    print(current_user.is_authenticated)
    if current_user.is_authenticated:
        return render_template('index.html')
    return redirect(url_for('login'))


# 定义一个路由，处理 /login 路径的请求，支持 GET 和 POST 方法
@app.route('/login', methods=['GET', 'POST'])
def login():
    # 检查请求方法是否为 POST
    if request.method == 'POST':
        # 从表单中获取用户名
        username = request.form['username']
        # 从表单中获取密码
        password = request.form['password']
        # 创建 PostgreSQLWrapper 类的实例，用于与数据库交互
        db = PostgreSQLWrapper()
        # 调用数据库方法，验证用户输入的用户名和密码是否正确
        user = db.authenticate_user(username, password)
        # 如果用户验证成功
        if user:
            # 登录用户
            login_user(user)
            # 重定向到首页
            return render_template('index.html')
        # 如果用户验证失败，返回登录页面并显示错误信息
        return render_template('login.html', error='用户名或密码错误')
    # 如果请求方法为 GET，直接返回登录页面
    return render_template('login.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/page1')
@login_required
def page1():
    return render_template('page1.html')

@app.route('/page2')
@login_required
def page2():
    return render_template('page2.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        invite_code = request.form['invite_code']
        db = PostgreSQLWrapper()
        print(username,password,invite_code)
        print(db.verify_invite_code(invite_code))
        if not db.verify_invite_code(invite_code):
            return render_template('register.html', error='邀请码无效')
        elif db.create_user(username, password):
            # return redirect(url_for('login', error='注册成功，请登录'))
            return render_template('login.html', error='注册成功，请登录')
        else:
            return render_template('register.html', error='注册失败')
    return render_template('register.html')

@app.route('/query_ips')
def query_ips():
    db = PostgreSQLWrapper()
    ippz = db.get_top_100_ip_configs()
    print("ip",ippz)
    return jsonify([{
        'id': ip[0],
        'line': ip[1],
        'address': ip[2],
        'software': ip[3],
        'product_type': ip[4]
    } for ip in ippz])

@app.route('/edit_ip/<id>', methods=['GET', 'POST'])
@login_required
def edit_ip(id):
    db = PostgreSQLWrapper()
    if request.method == 'POST':
        line = request.form['line']
        address = request.form['address']
        software = request.form['software']
        product_type = request.form['product_type']
        if not db.is_line_type_unique(line, id):
            return render_template('edit_ip.html', ip=db.get_ip_config_by_id(id), error='线别已存在,请重新输入')
        if not db.is_ip_address_unique(address, id):
            return render_template('edit_ip.html', ip=db.get_ip_config_by_id(id), error='IP地址已存在,请重新输入')
        db.update_ip_config(id, line, address, software, product_type)
        return redirect(url_for('page1'))
    ip = db.get_ip_config_by_id(id)
    print("我的IP",ip)
    return render_template('edit_ip.html', ip=ip)

@app.route('/delete_ip/<id>')
@login_required
def delete_ip(id):
    db = PostgreSQLWrapper()
    db.delete_ip_config(id)
    return redirect(url_for('page1'))

if __name__ == '__main__':
    app.run(debug=True)